package com.heima.leetcode.practice;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 103. 二叉树的锯齿形层序遍历
 * @date 2025/5/21 11:13
 */
public class E103 {

    @SuppressWarnings("all")
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        if (root == null) return result;
        int level = 1;
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode last = queue.poll();
                if (last.left != null) {
                    queue.offer(last.left);
                }
                if (last.right != null) {
                    queue.offer(last.right);
                }
                list.add(last.val);
            }
            if ((level & 1) == 0) {
                Collections.reverse(list);
            }
            result.add(list);
            level++;
        }
        return result;
    }
}
